import subprocess

import requests
from bs4 import BeautifulSoup

from installer import Installer
from system_info import get_system_info


def get_files(mirror_url):
    # 设置请求头，模拟浏览器访问
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/116.0.0.0 Safari/537.36"
    }
    # 发送HTTP请求
    response = requests.get(mirror_url, headers=headers, verify=False)
    # 检查请求是否成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析HTML内容
        soup = BeautifulSoup(response.text, "html.parser")
        # 假设文件列表在<a>标签的href属性中
        file_list = []
        for a_tag in soup.find_all("a", href=True):
            file_list.append(a_tag["href"])
        # 打印文件列表
        return file_list
    else:
        print(f"请求失败，状态码: {response.status_code}")
        return []


class Package:
    def __init__(self):
        self.name = ''
        self.version = ''
        self.url = ''
        self.cpu = ''


if __name__ == '__main__':
    system_info = get_system_info()
    import importlib

    system = system_info.system
    # 动态加载模块
    module = importlib.import_module(f"impls.{system}")
    Installer = getattr(module, 'InstallerImpl')
    installer = Installer()
    # 目标镜像网站的URL
    url = (f"https://mirrors.ustc.edu.cn/docker-ce/{system_info.os}/{system}/dists/{system_info.codename}"
           f"/pool/stable/{system_info.cpu}/")
    files = installer.filter(get_files(url))

    target_files = {}

    for file in files:
        split = file.split('_')
        version = split[1]
        file_name = split[0]
        if file_name not in target_files:
            target_files[file_name] = file
            continue
        if version > target_files[file_name].split('_')[1]:
            target_files[file_name] = file
    for file_name, file in target_files.items():
        subprocess.run(["wget", "--no-check-certificate", "-P", "/tmp", f'{url}{file}'])

    local_files = [f'/tmp/{file_name}' for file_name in target_files.values()]
    subprocess.run(["dpkg", "-i", *local_files])
